package at.fhooe.mc.msports.heartrate;

import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;

import net.rim.device.api.io.IOUtilities;
import at.fhooe.mc.msports.IGps;
import at.fhooe.mc.utils.Utils;

public class SimHRM extends Thread implements IHeartRateMonitor {
	int DELAY_MS = 2000;
	public String[] heartRateData = null;
	Vector listeners=new Vector();
	public boolean running = true;
	
	public SimHRM() {
		InputStream rStream = null;
		String path = "/lichtenberg.CSV";
		StringBuffer sb = new StringBuffer();
		try {
			rStream = getClass().getResourceAsStream(path);
		} finally {
			try {
				if (rStream != null) {
					byte[] data = IOUtilities.streamToBytes(rStream);
					sb.append(new String(data));
					heartRateData = Utils.split(sb.toString(), "\n");
					rStream.close();
				}
			} catch (IOException e) {
				System.out.println(e.getMessage());
			}
		}
	}

	public int getHeartRate() {
		// TODO Auto-generated method stub
		return 0;
	}

	public void addListener(IHeartRateListener listener) {
		listeners.addElement(listener);
	}
	public void informListener(int heartRate){
		for (int i = 0; i < listeners.size(); i++) {
			((IHeartRateListener) listeners.elementAt(i)).onHeartRateUpdated(heartRate);
		}
	}
	
	public void setRunning(boolean r){
		running = r;
	}
	
	public void run() {
		int i=0;
		String data=null;
		int heartRate=0;
		while (running) {
			for(i=0;i<heartRateData.length;i++){
				data=heartRateData[i];
				heartRate=Integer.valueOf(Utils.split(data, ";")[1]).intValue();
				informListener(heartRate);
				try {
					sleep(DELAY_MS);
					

				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if(i==heartRateData.length)
				i=0;
			
		}
	}

}
